package team.bluepen.supermarket.web.servlet;

import team.bluepen.supermarket.constant.Error;
import team.bluepen.supermarket.data.hdfs.HdfsManager;
import team.bluepen.supermarket.util.FileUtil;
import team.bluepen.supermarket.util.StringUtil;
import team.bluepen.supermarket.web.base.DataServlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Kai
 */
@WebServlet(name = "HdfsDownloadServlet", urlPatterns = "/api/download")
public class HdfsDownloadServlet extends DataServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
        String path = req.getParameter("path");
        if (StringUtil.isEmpty(path)) {
            resp.sendRedirect(requestSource + "?error=" + Error.ERROR_NULL);
            return;
        }
        String downloadName = FileUtil.getFileName(path);
        resp.setContentType("text/text;charset=utf-8");
        resp.setContentType("application/x-msdownload;charset=UTF-8");
        resp.setHeader("Content-Disposition", "attachment; filename=" + downloadName);
        ServletOutputStream stream = resp.getOutputStream();
        HdfsManager.getInstance().download(path, stream);

        stream.close();
        resp.sendRedirect("/");
    }
}
